/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import opiam.admin.applis.demo.beans.Person;

import opiam.admin.faare.SearchResult;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.services.SortService;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.List;


/**
 * This action allows to add in the temporary list all the users.
 * 
 * HTTP PARAMETERS :<br>
 * <li>cartname : target list name</li>
 */
public class AddAllToCartAction extends SecureAction
{
    /** logger de log4j */
    private static Logger _logger = Logger.getLogger(AddAllToCartAction.class);

    /**
     * This method is called to execute the action once the checks have been
     * performed by the SecureAction class.
     *
     * @param mapping              Struts mapping data.
     * @param actionForm           FormBean associated with the action.
     * @param request              HTTP request.
     * @param httpServletResponse  HTTP response.
     *
     * @return An ActionForward.
     *
     * @throws IOException  An I/O exception if failed or interrupted I/O operations occurs.
     * @throws ServletException  A ServletException if the servlet has a problem.
     */
    @Override
	public org.apache.struts.action.ActionForward secureExecute(org.apache.struts.action.ActionMapping mapping,
                                                                org.apache.struts.action.ActionForm actionForm,
                                                                javax.servlet.http.HttpServletRequest request,
                                                                javax.servlet.http.HttpServletResponse httpServletResponse
                                                               )
        throws java.io.IOException, javax.servlet.ServletException
    {
        // Gets the cartname
        String cartname = request.getParameter("cartname");

        _logger.debug("cartname = " + cartname);

        SessionContext sessionContext = null;
        UserContext userContext = null;
        ActionMessages msgErrors = new ActionMessages();

        try
        {
            // Gets the session.
            HttpSession session = request.getSession();
            // Gets the session context.
            sessionContext = SessionContext.getInstance(session);
            // Gets the user context.
            userContext = sessionContext.getUserContext();

            // Gets the temporary list
            List currentCart = (List) session.getAttribute(cartname);

            // Creates and puts this list in the session if it does not exist
            if (currentCart == null)
            {
                _logger.debug("cart " + cartname + " is null, will be created");
            }

            currentCart = new ArrayList();

            // Gets the search results
            SearchResult result =
                (SearchResult) session.getAttribute("searchResult");
            List results = result.getLResults();

            // Add the search result to the temporary list
            for (int i = 0; i < results.size(); i++)
            {
                currentCart.add(results.get(i));
            }

            // Sorts the list
            SortService.sort(currentCart, Person.class, "name",
                             SessionContext.getInstance(session).getUserContext()
                            );

            // Returns the list 
            session.setAttribute(cartname, currentCart);
            request.setAttribute("cartname", cartname);

            _logger.debug("Forward success : " +
                          mapping.findForward("success").toString()
                         );

            // Manages the display of the tempList icon
            boolean indic = userContext.getParameters().containsKey("cartIndic");
            if (!indic)
            {
            	userContext.getParameters().put("cartIndic", "cartname");
            }

            
            return (mapping.findForward("success"));
        }
        catch (Exception se)
        {
            _logger.error(se.getMessage());
            msgErrors.add(ActionMessages.GLOBAL_MESSAGE,
                          new ActionMessage("error.service.unknown")
                         );
            saveErrors(request, msgErrors);

            return (mapping.findForward("service_error"));
        }
    }
}
